/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package py.com.spadons.esmetil.controllers.jsf;

import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import py.com.spadons.esmetil.entities.Usuario;
import py.com.spadons.security.servicios.StringMD;

/**
 *
 * @author spadons
 */
@ManagedBean
@SessionScoped
public class UsuarioPerfilController implements Serializable{
    @EJB
    private py.com.spadons.esmetil.sessionBeans.UsuarioFacade usuarioFacade;
    private Usuario usuario;
    private String password1;
    private String password2;

    public UsuarioPerfilController() {
    }
    
    @PostConstruct
    public void inicializar(){
        
        FacesContext facesCtx = FacesContext.getCurrentInstance();
        ELContext elCtx = facesCtx.getELContext();
        ExpressionFactory expFact = facesCtx.getApplication().getExpressionFactory();
                      
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName(); //get logged in username
      
        usuario = usuarioFacade.find(name);  
        
    }

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    public String getPassword1() {
        return password1;
    }

    public void setPassword1(String password1) {
        StringMD.getStringMessageDigest(password1,StringMD.SHA1);
        this.password1 = StringMD.getStringMessageDigest(password1,StringMD.SHA1);
    }

    public String getPassword2() {
        return password2;
    }

    public void setPassword2(String password2) {
        this.password2 = StringMD.getStringMessageDigest(password2,StringMD.SHA1);
    }
    
    public void cambiarContraseña(){
        if(getPassword1().equals(getPassword2())){
            usuario.setPassword(getPassword1());
            usuarioFacade.edit(usuario);
            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Correcto", "La contraseña fue cambiada con éxito"));
            
        }else{
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error", "Las Contraseña no coinciden"));
        }
        
    }
    
}
